/**
    @project {
        "templateId": "org.helgoboss.custom",
        "version": "0.1-SNAPSHOT",
        "dependencies": [
            "org.scala-lang:scala-library:2.9.0-1",
            "org.helgoboss:osgi-additions:0.1-SNAPSHOT",
            "org.helgoboss:obr-facade-api:0.3-SNAPSHOT"
        ]
    }
*/

package org.helgoboss.automatic_obr_installer

import org.helgoboss.osgi_additions._
import org.osgi.service.packageadmin.PackageAdmin
import org.helgoboss.obr_facade._
import org.osgi.framework.Bundle
import java.net.URL

class Activator extends OsgiContext with OsgiConfigurationWatcher with OsgiLogging with OsgiServiceWatcher {
    whenBundleActive {
        whenServicePresent[ObrFacade] { obrFacade =>
                        
        
            whenConfigurationUpdated("org.helgoboss.automatic_obr_installer") { conf =>
                conf.foreach { c =>
                    obrFacade.installedLocalRepositories.foreach(obrFacade.refreshRepository)
                
                    c.get("repositories").map(_.toString).foreach { urlStrings =>
                        val repositoryUrlStrings = urlStrings.split(",").map(_.trim).filterNot(_.isEmpty)
                        repositoryUrlStrings.foreach { urlString =>
                            val url = new URL(urlString)
                            if (!obrFacade.repositoryIsInstalled(url)) {
                                obrFacade.installRepository(url)
                            }
                        }
                    }
                    c.get("resources").map(_.toString).foreach { r =>
                        val resourceExpressions = r.split(",").map(_.trim).filterNot(_.isEmpty)
                        val resourceIds = resourceExpressions.map { e =>
                            val components = e.split(":")
                            ResourceId(symbolicName = components(0), version = components(1))                            
                        }.filterNot(obrFacade.resourceIsSwitchedOn)
                        obrFacade.switchOnResources(resourceIds)
                    }
                }
            }
        }
    }
    
}
